'use client'

import Image from 'next/image'
import searchIcon from '@/public/search_black.png'
import { FormEvent, useState } from 'react'
import { useRouter } from 'next-nprogress-bar'
import { usePathname, useSearchParams } from 'next/navigation'

interface SearchBarProps {
  defaultValue: string
}

const SearchBar: React.FC<SearchBarProps> = (props) => {
  const { defaultValue } = props
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const router = useRouter()
  const [searchText, setSearchText] = useState(defaultValue)
  const handleInput = (e: FormEvent) => {
    setSearchText((e.target as HTMLInputElement).value)
  }
  const handleKeyUp = (e: any) => {
    if (e.key === 'Enter') {
      const params = new URLSearchParams(searchParams)
      if (searchText) {
        params.set('keyword', searchText)
      } else {
        params.delete('keyword')
      }
      router.replace(`${pathname}?${params.toString()}`)
    }
  }
  return (
    <div className='rounded-full w-full flex items-center space-x-2 px-[0.9375rem] bg-[#F8F8F8] lg:max-w-[9.5625rem] lg:text-[0.75rem] 2xl:text-[1.125rem] 2xl:px-[1.40625rem] 2xl:max-w-[14.34375rem]'>
      <div className='relative w-3 h-3 2xl:w-[1.125rem] 2xl:h-[1.125rem]'>
        <Image
          src={searchIcon}
          alt='search icon'
          fill
          sizes='(max-width: 1024px) 5vw'
        />
      </div>
      <input
        value={searchText}
        type='text'
        enterKeyHint='search'
        className='w-full h-9 outline-none bg-transparent lg:h-10 2xl:h-[3.75rem]'
        placeholder='keywords'
        onInput={handleInput}
        onKeyUp={handleKeyUp}
      />
    </div>
  )
}

export default SearchBar
